<script setup lang="ts">
import { RouterView } from 'vue-router'
import { useStore } from "@/stores/user";
import { someFieldStore } from '@/stores/somefield';
import { getUrlParams, getUrlParamValue } from "@/utils/getUrlParams";
import API from "@/service/api/login";
import { request } from "@/service/request";
import { useDynamicKeepAlive } from '@/utils/keepAliveUtils'
import { useKeepAliveStore } from '@/stores/keepalive'

const mSomeField = someFieldStore();
const urlParamsArr = getUrlParams();
if (Array.isArray(urlParamsArr) && urlParamsArr.length > 0) {
  if (!Array.isArray(mSomeField.clientfields)) {
    mSomeField.clientfields = [];
  }
  urlParamsArr.forEach(param => {
    const idx = mSomeField.clientfields.findIndex((item: any) => item.key === param.key);
    if (idx !== -1) {
      // 已有则替换
      mSomeField.clientfields[idx] = param;
    } else {
      // 没有则追加
      mSomeField.clientfields.push(param);
    }
  });
}


const mUser = useStore();

const clkGetInfo = async () => {
  const { data } = await request.post<any>(API.inFo);
  mSomeField.order_num= '';  //客户端登录清空本地工单号
  mUser.token.user_name = data.user_name;
  mUser.token.uid = data.uid;
  mUser.state = true;
};


if (getUrlParamValue('access_token', mSomeField.clientfields) != null && getUrlParamValue('access_token', mSomeField.clientfields) != '') {
  mUser.$reset(); //如果有可用token就清空本地的token
  mUser.token.user.access_token = getUrlParamValue('access_token', mSomeField.clientfields);
  clkGetInfo()
}else if(getUrlParamValue('access_token', mSomeField.clientfields) != null && getUrlParamValue('access_token', mSomeField.clientfields) == ''){
  mUser.$reset(); //客户端传token为空就清空本地的token
}

useDynamicKeepAlive()
const keepAlive = useKeepAliveStore()

</script>

<template>
  <router-view v-slot="{ Component }">
    <keep-alive :include="keepAlive.cachedViews">
      <component :is="Component" />
    </keep-alive>
  </router-view>
</template>